package com.wsc.wisdomchinaqinghe.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.wsc.wisdomchinaqinghe.R;
import com.wsc.wisdomchinaqinghe.Tools.ACache;
import com.wsc.wisdomchinaqinghe.Tools.JsonTools;
import com.wsc.wisdomchinaqinghe.Tools.Tools;
import com.wsc.wisdomchinaqinghe.activitity.fourmodule.HelpOldManDetailActivity;
import com.wsc.wisdomchinaqinghe.adapter.AroundFindAdapter;
import com.wsc.wisdomchinaqinghe.application.MyApplication;
import com.wsc.wisdomchinaqinghe.callback.ContributorView;
import com.wsc.wisdomchinaqinghe.javaBean.AroundFindListBean;
import com.wsc.wisdomchinaqinghe.javaBean.RespObj;
import com.wsc.wisdomchinaqinghe.presenter.ContributorPresenter;

import java.util.List;

/**
 * @author jaily.zhang
 * @version V1.3.1
 * @Description 选中的行业标签
 * @date 2015-4-29 下午4:47:24
 */
public class EightModuleFragment extends Fragment implements ContributorView {
    private PullToRefreshListView lv_today_information;
    private ListView actualListView;
    private final String EightModuleFragment = EightModuleFragment.class.getSimpleName();

    private String cid;
    private int type;
    private Context mcontext;
    private int skip = 0;
    private final int limit = 6;
    private ContributorPresenter contributorPresenter;
    private final String HOME_NEWS = EightModuleFragment;
    private List<AroundFindListBean> homeNewsList;
    private AroundFindAdapter quanBuAdapter;
    private boolean isfresh = true;
    private ProgressBar pb_todayInfo;
    private MyApplication myApplication;
    private ACache aCache;
    private String aCacheFlagKey;


    public static EightModuleFragment newInstance(Bundle b) {
        EightModuleFragment selectedOneFragment = new EightModuleFragment();
        selectedOneFragment.setArguments(b);
        return selectedOneFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        cid = getArguments().getString("cid");
        type=getArguments().getInt("type");
        aCacheFlagKey=EightModuleFragment+type;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.hotnewsfragment_layout, container, false);
        mcontext = getActivity();
        aCache=ACache.get(mcontext);
        myApplication=(MyApplication) getActivity().getApplication();
        contributorPresenter = new ContributorPresenter(this, mcontext);
        initView(view);
        return view;
    }

    /**
     * @param view
     * @Description 初始化View控件
     * @author jaily.zhang
     */
    private void initView(View view) {

        lv_today_information = (PullToRefreshListView) view.findViewById(R.id.lv_today_information);
        lv_today_information.setMode(Mode.BOTH);
        pb_todayInfo = (ProgressBar) view.findViewById(R.id.pb_todayInfo);
        actualListView = lv_today_information.getRefreshableView();

        actualListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        actualListView.setDivider(null);
        Tools.showRefreshView(lv_today_information);

        lv_today_information.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                // TODO Auto-generated method stub
                // Update the LastUpdatedLabe
                // 处理下拉刷新的业务
                if (refreshView.getCurrentMode().equals(Mode.PULL_FROM_START)) {
                    isfresh = true;
                    Tools.showRefreshView(lv_today_information);
                    skip = 0;
                    //首页资讯
                    contributorPresenter.getAroundFindList(cid, type, skip, limit, HOME_NEWS);
                } else {
                    isfresh = false;
                    Tools.showRefreshView(lv_today_information);
                    skip += limit;
                    //首页资讯
                    contributorPresenter.getAroundFindList(cid, type, skip, limit, HOME_NEWS);
                }

            }
        });

        actualListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Intent intent = new Intent(mcontext, HelpOldManDetailActivity.class);
                intent.putExtra("id", homeNewsList.get(position-1).getId());
                intent.putExtra("name", homeNewsList.get(position-1).getTitle());
                intent.putExtra("nameFlag", "EightModule");
                intent.putExtra("imagesrc",homeNewsList.get(position-1).getGuideImg());
                startActivity(intent);
            }
        });
    }

    /**
     * @Description 服务器获取数据
     * @author jaily.zhang
     */
    private void showData() {
        if(aCache.getAsString(aCacheFlagKey)!=null)
        {
            pb_todayInfo.setVisibility(View.GONE);
            List<AroundFindListBean> homeNewsItem = JsonTools.jsonStringToList(aCache.getAsString(aCacheFlagKey), AroundFindListBean.class);
            if (homeNewsItem != null && homeNewsItem.size() > 0) {
                homeNewsList = homeNewsItem;
                quanBuAdapter = new AroundFindAdapter(mcontext, homeNewsList);
                actualListView.setAdapter(quanBuAdapter);
            }
        }else
        {
            //首页资讯
            contributorPresenter.getAroundFindList(cid, type, skip, limit, HOME_NEWS);
        }

    }


    @Override
    public void onLoadContributorStart(String flag) {

    }


    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        try {
            if (flag.equals(HOME_NEWS)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    String jsonMessage = JsonTools.objectToJsonString(object);
                    List<AroundFindListBean> homeNewsItem = JsonTools.jsonStringToList(jsonMessage, AroundFindListBean.class);
                    if (homeNewsItem != null && homeNewsItem.size() > 0) {
                        if (isfresh) {
                            aCache.put(aCacheFlagKey,jsonMessage,8*60);
                            homeNewsList = homeNewsItem;
                            quanBuAdapter = new AroundFindAdapter(mcontext, homeNewsList);
                            actualListView.setAdapter(quanBuAdapter);
                        } else {
                            homeNewsList.addAll(homeNewsItem);
                            quanBuAdapter.notifyDataSetChanged();
                        }

                    }

                }
            }
        }catch (Exception e)
        {

        }
    }


    @Override
    public void onLoadContributorComplete(String flag) {
        lv_today_information.onRefreshComplete();
        pb_todayInfo.setVisibility(View.GONE);
    }

    @Override
    public void onLoadContributorError(String error, String flag) {
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (myApplication.getInformationFragmentSelected() != null) {
            if (myApplication.getInformationFragmentSelected().equals(EightModuleFragment + type)) {
                isfresh = true;
                skip = 0;
                showData();
            }
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

}
